#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>



#define SIZE 1024
char* argv[SIZE];


const char* GetHostName()
{
    char* hostname = getenv("HOSTNAME");
    
    if (hostname) return hostname;
    else return "None";
}

const char* GetUser()
{
    char* user = getenv("USER");

    if (user) return user;
    else return "None";
}

const char* GetPwd()
{
    char* pwd = getenv("PWD");

    if (pwd) return pwd;
    else return "None";
}

const char* GetHome()
{
    char* home = getenv("HOME");
    if (home) return home;
    else return "None";
}

void ReceiveInstruction(char* in)
{

    printf("[%s@%s %s]$ ", GetUser(), GetHostName(), GetPwd());
 
    fgets(in, SIZE, stdin);
    in[strlen(in)-1] = '\0';
}


void ProcessInstruction(char* in)
{
    int i = 0;    
    argv[i++] = strtok(in, " ");
    while (argv[i++] = strtok(NULL, " "));
}


int BuiltinCommand()
{
    int ret = 0;
    if (strcmp(argv[0], "cd") == 0)
    {
        ret = 1;
        if (strcmp(argv[1], "..") == 0)
        {
            chdir("..");
        }
        else if (argv[1] == NULL)
        {
            chdir(GetHome());
        }
    }

    return ret;
}


void ExecutionInstruction()
{
    pid_t id = fork();

    if (id == 0)
    {
        // child
        execvp(argv[0], argv);
        exit(1);
    }

    pid_t rid = waitpid(id, NULL, 0);
//    if (rid > 0)
//    {
//        printf("wait success..\n");
//    }
}

int main()
{
    while (1)
    {
        char commandline[SIZE];
        // 1. 接收指令
        ReceiveInstruction(commandline);

        // printf("%s\n", commandline);
        
        
        // 2. 处理指令
        ProcessInstruction(commandline);
        // 3. 内建命令
        int n = BuiltinCommand(); 
        if (n) continue;
        // 4. 执行指令
        ExecutionInstruction();
    }
    // father

    //int j;
    //for (j = 0; argv[j]; j++)
    //{
    //    printf("argv[%d]: %s\n", j, argv[j]);
    //}



    return 0;
}
